package com.ruyiadmin.springboot.web_api.controllers.system_controllers;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruyiadmin.springboot.common_infrastructure.constants.system.ExceptionMessage;
import com.ruyiadmin.springboot.web_api.annotations.system.OperationLog;
import com.ruyiadmin.springboot.web_api.annotations.system.Permission;
import com.ruyiadmin.springboot.common_infrastructure.models.SearchCondition;
import com.ruyiadmin.springboot.common_infrastructure.models.SearchItem;
import com.ruyiadmin.springboot.common_infrastructure.enums.business.OperationType;
import com.ruyiadmin.springboot.common_infrastructure.models.ActionResponseResult;
import com.ruyiadmin.springboot.common_infrastructure.models.QueryResponseResult;
import com.ruyiadmin.springboot.common_infrastructure.enums.framework.DataType;
import com.ruyiadmin.springboot.common_infrastructure.enums.framework.SearchMethod;
import com.ruyiadmin.springboot.common_infrastructure.exceptions.RuYiAdminCustomException;
import com.ruyiadmin.springboot.entity_data_model.entity_model.system_model.SysImportConfig;
import com.ruyiadmin.springboot.entity_data_model.entity_model.system_model.SysImportConfigDetail;
import com.ruyiadmin.springboot.service_layer.interfaces.system_interfaces.ISysImportConfigDetailService;
import com.ruyiadmin.springboot.service_layer.interfaces.system_interfaces.ISysImportConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

/**
 * <p>
 * 导入配置主表 前端控制器
 * </p>
 *
 * @author RuYiAdmin
 * @since 2022-07-12
 */
@RestController
@RequestMapping("/ImportConfigManagement")
@Api(tags = "系统导入配置管理服务")
@RequiredArgsConstructor
public class SysImportConfigController {

    //region 配置服务私有属性

    private final ISysImportConfigService importConfigService;
    private final ISysImportConfigDetailService detailService;

    //endregion

    //region 查询导入配置列表

    @PostMapping("/Post")
    @ApiOperation(value = "查询导入配置列表")
    @OperationLog(operationType = OperationType.QueryList)
    @Permission(permission = "import:config:query:list")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public QueryResponseResult<SysImportConfig> queryByPage(@RequestBody SearchCondition searchCondition)
            throws ExecutionException, InterruptedException {
        CompletableFuture<QueryResponseResult<SysImportConfig>> future = CompletableFuture.supplyAsync(() -> {
            QueryWrapper<SysImportConfig> wrapper = new QueryWrapper<>();//设置条件
            searchCondition.convertToQueryWrapper(wrapper);//转化查询条件、转化排序条件
            Page<SysImportConfig> page = new Page<>(searchCondition.getPageIndex(),
                    searchCondition.getPageSize());//初始化page

            this.importConfigService.page(page, wrapper);//执行查询
            long total = page.getTotal();//总数
            List<SysImportConfig> rs = page.getRecords();//结果

            return QueryResponseResult.success(total, rs);
        });
        return future.get();
    }

    //endregion

    //region 按编号获取导入配置

    @GetMapping("/GetById/{id}")
    @ApiOperation(value = "按编号获取导入配置")
    @OperationLog(operationType = OperationType.QueryEntity)
    @Permission(permission = "import:config:query:list")
    public ActionResponseResult getById(@PathVariable("id") String id) throws ExecutionException, InterruptedException {
        CompletableFuture<ActionResponseResult> future = CompletableFuture.supplyAsync(() ->
                ActionResponseResult.success(this.importConfigService.getById(id)));
        return future.get();
    }

    //endregion

    //region 新增导入配置信息

    @PostMapping("/AddConfig")
    @ApiOperation(value = "新增导入配置信息")
    @OperationLog(operationType = OperationType.AddEntity)
    @Permission(permission = "import:config:add:entity")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ActionResponseResult add(@Valid @RequestBody SysImportConfig importConfig) {
        return ActionResponseResult.success(this.importConfigService.save(importConfig));
    }

    //endregion

    //region 修改导入配置信息

    @PutMapping("/EditConfig")
    @ApiOperation(value = "修改导入配置信息")
    @OperationLog(operationType = OperationType.EditEntity)
    @Permission(permission = "import:config:edit:entity")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ActionResponseResult edit(@Valid @RequestBody SysImportConfig importConfig) {
        return ActionResponseResult.success(this.importConfigService.updateById(importConfig));
    }

    //endregion

    //region 批量删除导入配置信息

    @DeleteMapping("/DeleteConfigs/{ids}")
    @ApiOperation(value = "批量删除导入配置信息")
    @OperationLog(operationType = OperationType.DeleteEntity)
    @Permission(permission = "import:config:del:entities")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ActionResponseResult deleteRange(@PathVariable("ids") String ids) {
        //导入配置信息删除检测
        this.deleteCheck(ids);
        //删除数据
        List<String> array = Arrays.asList(ids.split(","));
        return ActionResponseResult.success(this.importConfigService.removeByIds(array));
    }

    //endregion

    //region 导入配置信息删除检测

    /**
     * 导入配置信息删除检测
     *
     * @param ids 编号数组
     */
    private void deleteCheck(String ids) {
        String[] array = ids.split(",");
        //删除校验
        for (String item : array) {
            SearchCondition searchCondition = new SearchCondition();
            searchCondition.setSearchItems(new ArrayList<>());
            searchCondition.getSearchItems().add(new SearchItem("PARENT_ID", DataType.Guid, SearchMethod.Equal, item));
            QueryWrapper<SysImportConfigDetail> wrapper = new QueryWrapper<>();
            searchCondition.convertToQueryWrapper(wrapper);
            int count = this.detailService.list(wrapper).size();
            if (count > 0) {
                throw new RuYiAdminCustomException(ExceptionMessage.DeleteImportConfigExceptionMessage);
            }
        }
    }

    //endregion

    //region 按父键获取配置明细

    @GetMapping("/GetByParentId/{parentId}")
    @ApiOperation(value = "按父键获取配置明细")
    @OperationLog(operationType = OperationType.QueryList)
    @Permission(permission = "import:config:query:list")
    public ActionResponseResult getByParentId(@PathVariable("parentId") String parentId)
            throws ExecutionException, InterruptedException {
        CompletableFuture<ActionResponseResult> future = CompletableFuture.supplyAsync(() -> {
            SearchCondition searchCondition = new SearchCondition();
            searchCondition.setSearchItems(new ArrayList<>());
            searchCondition.getSearchItems().add(
                    new SearchItem("PARENT_ID", DataType.Guid, SearchMethod.Equal, parentId));

            QueryWrapper<SysImportConfigDetail> wrapper = new QueryWrapper<>();
            searchCondition.convertToQueryWrapper(wrapper);

            List<SysImportConfigDetail> list = this.detailService.list(wrapper)
                    .stream()
                    .sorted(Comparator.comparing(SysImportConfigDetail::getCreateTime))
                    .collect(Collectors.toList());

            return ActionResponseResult.success(list);
        });
        return future.get();
    }

    //endregion

    //region 添加导入配置明细

    @PostMapping("/AddConfigDetail")
    @ApiOperation(value = "添加导入配置明细")
    @OperationLog(operationType = OperationType.AddEntity)
    @Permission(permission = "import:config:add:entity")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ActionResponseResult add(@Valid @RequestBody SysImportConfigDetail configDetail) {
        return ActionResponseResult.success(this.detailService.save(configDetail));
    }

    //endregion

    //region 编辑导入配置明细

    @PutMapping("/EditConfigDetail")
    @ApiOperation(value = "编辑导入配置明细")
    @OperationLog(operationType = OperationType.EditEntity)
    @Permission(permission = "import:config:edit:entity")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ActionResponseResult edit(@Valid @RequestBody SysImportConfigDetail configDetail) {
        return ActionResponseResult.success(this.detailService.updateById(configDetail));
    }

    //endregion

    //region 批量删除配置明细

    @DeleteMapping("/DeleteConfigDetails/{ids}")
    @ApiOperation(value = "批量删除配置明细")
    @OperationLog(operationType = OperationType.DeleteEntity)
    @Permission(permission = "import:config:del:entities")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ActionResponseResult deleteDetailRange(@PathVariable("ids") String ids) {
        //删除数据
        List<String> array = Arrays.asList(ids.split(","));
        return ActionResponseResult.success(this.detailService.removeByIds(array));
    }

    //endregion

}
